
import { wsStore } from "@/store/ws.js";
import {msgStore} from "@/store/msg.js";

let store = wsStore();
let mStore = msgStore();
const url = "ws://localhost:8004/ws"


/**
 * 发送消息
 * @param data
 */
function sendMsg(data){
    data.token = localStorage.getItem("wx_token")
    if (store.ws && store.ws.readyState!==WebSocket.CONNECTING) {
        store.ws.send(JSON.stringify(data))
    }else {
        setTimeout(()=>{
            store.ws.send(JSON.stringify(data))
        },1000)
    }
}

/**
 * 心跳检测
 */
function heartbeatCheck(){
    if (store.ws && store.ws.readyState===WebSocket.OPEN) {
        store.task = setInterval(()=>{
            let heart = {
                ping:"ping"
            }
            sendMsg(heart)
        },3000)
    }else {
        if (store.ws && store.ws.readyState!==WebSocket.CONNECTING){
            // reConnect()
        }
    }
}

/**
 * 断开重连
 */
function reConnect(){
    init();
}

/**
 * 关闭连接
 */
export function wsClose(){
    if (store.task) {
        clearInterval(store.task)
    }
    if (store.ws){
        store.ws.close();
        store.ws = null;
    }
}

/**
 * 初始化
 */
function init(){
    let websocket = new WebSocket(url);
    websocket.onopen=()=>{
        heartbeatCheck()
    }
    websocket.onmessage=(res)=>{
        if (res.data==='fail auth'){
            setTimeout(()=>{
                wsClose()
            },1000)
        }else {
            if (res.data!=='pong'){
                if (res.data){
                    mStore.msg = JSON.parse(res.data)
                }
            }
        }
    }
    websocket.onclose = ()=>{
        console.log("连接被动断开")
    }
    store.ws = websocket;
}
/**
 * 创建消息发送
 * @param data
 */
export default function socketSend(data){
    if (store.ws==null){
        init()
    }
    sendMsg(data)
}